import { ExportOutlined, FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons'
import { Button, Flex, DatePicker, Card, Typography, Tabs, Segmented, Empty, Spin, message } from 'antd'
import React, { useState, useEffect } from 'react'
import icon from '@/assets/images/enterprise/icon@2x.png'
import './index.scss'
import BarChart from '@/components/BarChart'
import PieChart from '@/components/PieChart'
import DistributionDiagram from '@/components/DistributionDiagram'
import RelationalGraph from '@/components/RelationalGraph'
import Jiaoyi from '@/components/Jiaoyi'
import dayjs from 'dayjs'
import { opponentAPI, tradecrowdAPI, exportgenerateAPI } from '@/apis'
import axios from 'axios'
import _ from 'lodash'
import { toggleFull } from '@/utils'
const { Paragraph, Title, Text } = Typography
const { RangePicker } = DatePicker


//获取当前单位类型,根据类型设定区域显示与隐藏
const IS_CYDW = localStorage.getItem("CURR_IS_CYDW")

const defaultMapData = [
  { name: "黑龙江", value: 0 },
  { name: "吉林", value: 0 },
  { name: "辽宁", value: 0 },
  { name: "内蒙古", value: 0 },
  { name: "河北", value: 0 },
  { name: "北京", value: 0 },
  { name: "天津", value: 0 },
  { name: "新疆", value: 0 },
  { name: "西藏", value: 0 },
  { name: "青海", value: 0 },
  { name: "甘肃", value: 0 },
  { name: "宁夏", value: 0 },
  { name: "山西", value: 0 },
  { name: "山东", value: 0 },
  { name: "陕西", value: 0 },
  { name: "河南", value: 0 },
  { name: "江苏", value: 0 },
  { name: "四川", value: 0 },
  { name: "重庆", value: 0 },
  { name: "湖北", value: 0 },
  { name: "安徽", value: 0 },
  { name: "上海", value: 0 },
  { name: "贵州", value: 0 },
  { name: "湖南", value: 0 },
  { name: "江西", value: 0 },
  { name: "浙江", value: 0 },
  { name: "云南", value: 0 },
  { name: "广西", value: 0 },
  { name: "广东", value: 0 },
  { name: "福建", value: 0 },
  { name: "海南", value: 0 },
  { name: "澳门", value: 0 },
  { name: "香港", value: 0 },
  { name: "台湾", value: 0 },
  { name: "南海诸岛", value: 0 }
]


// const dyxAxisData = ['北京', '上海', '广东', '山东', '四川']
// const dystatisticsData = {
//     yName: '对手数量(家)',
//     data: [
//         {
//             name: '',
//             data: [
//                 2.0, 5.0, 7.0, 23.0, 30.0
//             ]
//         }
//     ]
// }
// const hyxAxisData = ['大型企业', '中型企业', '小型企业', '微型企业']
// const hystatisticsData = {
//     yName: '对手数量(家)',
//     data: [
//         {
//             name: '上游',
//             data: [
//                 2.0, 4.9, 7.0, 23.2
//             ]
//         },
//         {
//             name: '下游',
//             data: [
//                 2.6, 5.9, 9.0, 26.4
//             ]
//         }
//     ]
// }
// const fbdataList = [
//     { name: '澳门', value: 18 },
//     { name: '香港', value: 273 },
//     { name: '台湾', value: 153 },
//     { name: '新疆', value: 76 },
//     { name: '宁夏', value: 75 },
//     { name: '青海', value: 18 },
//     { name: '甘肃', value: 134 },
//     { name: '陕西', value: 248 },
//     { name: '西藏', value: 1 },
//     { name: '云南', value: 176 },
//     { name: '贵州', value: 146 },
//     { name: '四川', value: 543 },
//     { name: '重庆', value: 576 },
//     { name: '海南', value: 168 },
//     { name: '广西', value: 254 },
//     { name: '广东', value: 1407 },
//     { name: '湖南', value: 1018 },
//     { name: '湖北', value: 678 },
//     { name: '河南', value: 1273 },
//     { name: '山东', value: 765 },
//     { name: '江西', value: 936 },
//     { name: '福建', value: 307 },
//     { name: '安徽', value: 990 },
//     { name: '浙江', value: 1237 },
//     { name: '江苏', value: 633 },
//     { name: '上海', value: 394 },
//     { name: '黑龙江', value: 484 },
//     { name: '吉林', value: 93 },
//     { name: '辽宁', value: 126 },
//     { name: '内蒙古', value: 75 },
//     { name: '山西', value: 133 },
//     { name: '河北', value: 319 },
// ]

export default function Duishoutezheng({ data }) {
    const chartBoxH = 360;
    const [isFullScreen, setIsFullScreen] = useState(false);
    const [chartBoxHeight, setChartBoxHeight] = useState(360)
    const [startDate, setStartDate] = useState(dayjs().startOf('year').format('YYYY-MM-DD'))
    const [endDate, setEndDate] = useState(dayjs(new Date()).format('YYYY-MM-DD'))
    // const [startDate, setStartDate] = useState('2024-01-01')
    // const [endDate, setEndDate] = useState('2024-12-31')
    const [feature, setfeature] = useState(null)
    const [duishou, setduishou] = useState(null)
    const [gmRatio, setgmRatio] = useState(null)
    const [gmtype, setgmtype] = useState('上游')
    const [hyRatio, sethyRatio] = useState(null)
    const [hytype, sethytype] = useState('上游')
    const [gmxAxisData, setgmxAxisData] = useState(null)
    const [gmstatisticsData, setgmstatisticsData] = useState(null)
    const [fbdataList, setfbdataList] = useState(defaultMapData)
    const [dyxAxisData, setdyxAxisData] = useState([])
    const [dystatisticsData, setdystatisticsData] = useState(null)
    const [hyxAxisData, sethyxAxisData] = useState(null)
    const [hystatisticsData, sethystatisticsData] = useState(null)
    const [isloading, setisloading] = useState(false)
    const [shequdata, setshequdata] = useState(null)
    const [messageApi, contextHolder] = message.useMessage();
    const handleDate = (time) => {
        setStartDate(dayjs(time[0]).format('YYYY-MM-DD'))
        setEndDate(dayjs(time[1]).format('YYYY-MM-DD'))
    }
    useEffect(() => {
        const handleKeyDown = () => {
            // 全屏
            if (document.fullscreenElement) {
                setIsFullScreen(true);
                setChartBoxHeight('100%')
            } else {
                setIsFullScreen(false);
                setChartBoxHeight(360)
            }
        };
        document.addEventListener('fullscreenchange', handleKeyDown);
    }, [])

    useEffect(() => {
        function getData() {
            setisloading(true)
            opponentAPI({
                company: data.company_info[0].GSMC,
                companytype: data.company_info[0].IS_CYDW,
                startDate,
                endDate
            }).then(res => {
                setfeature(res.data.max_info)
                if (res.data.dsgm_cydw.cydw_info.sxy_statistics.all_keys.length > 0) {
                    setgmxAxisData(res.data.dsgm_cydw.cydw_info.sxy_statistics.all_keys)
                    const gmsydata = []
                    const gmxydata = []
                    for (let i = 0; i < res.data.dsgm_cydw.cydw_info.sxy_statistics.all_keys.length; i++) {
                        for (let j = 0; j < res.data.dsgm_cydw.cydw_info.sxy_statistics.sy_normalized_list.length; j++) {
                            if (res.data.dsgm_cydw.cydw_info.sxy_statistics.all_keys[i] === res.data.dsgm_cydw.cydw_info.sxy_statistics.sy_normalized_list[j].name) {
                                gmsydata.push(res.data.dsgm_cydw.cydw_info.sxy_statistics.sy_normalized_list[j].value)
                            }
                        }
                        for (let j = 0; j < res.data.dsgm_cydw.cydw_info.sxy_statistics.xy_normalized_list.length; j++) {
                            if (res.data.dsgm_cydw.cydw_info.sxy_statistics.all_keys[i] === res.data.dsgm_cydw.cydw_info.sxy_statistics.xy_normalized_list[j].name) {
                                gmxydata.push(res.data.dsgm_cydw.cydw_info.sxy_statistics.xy_normalized_list[j].value)
                            }
                        }
                    }
                    setgmstatisticsData({
                        yName: '对手数量(家)',
                        data: [
                            {
                                name: '上游',
                                data: gmsydata
                            },
                            {
                                name: '下游',
                                data: gmxydata
                            }
                        ]
                    })
                }
                if (res.data.hyfb.dshy_info.sxy_statistics.all_keys.length > 0) {
                    sethyxAxisData(res.data.hyfb.dshy_info.sxy_statistics.all_keys)
                    const hysydata = []
                    const hyxydata = []
                    for (let i = 0; i < res.data.hyfb.dshy_info.sxy_statistics.all_keys.length; i++) {
                        for (let j = 0; j < res.data.hyfb.dshy_info.sxy_statistics.sy_normalized_list.length; j++) {
                            if (res.data.hyfb.dshy_info.sxy_statistics.all_keys[i] === res.data.hyfb.dshy_info.sxy_statistics.sy_normalized_list[j].name) {
                                hysydata.push(res.data.hyfb.dshy_info.sxy_statistics.sy_normalized_list[j].value)
                            }
                        }
                        for (let j = 0; j < res.data.hyfb.dshy_info.sxy_statistics.xy_normalized_list.length; j++) {
                            if (res.data.hyfb.dshy_info.sxy_statistics.all_keys[i] === res.data.hyfb.dshy_info.sxy_statistics.xy_normalized_list[j].name) {
                                hyxydata.push(res.data.hyfb.dshy_info.sxy_statistics.xy_normalized_list[j].value)
                            }
                        }
                    }
                    sethystatisticsData({
                        yName: '对手数量(家)',
                        data: [
                            {
                                name: '上游',
                                data: hysydata
                            },
                            {
                                name: '下游',
                                data: hyxydata
                            }
                        ]
                    })
                }
                setfbdataList(res.data.dyfb.dsdy_info.qgfb_data)
                setdyxAxisData(res.data.dyfb.dsdy_info.top5_sf)
                setdystatisticsData({
                    yName: '对手数量(家)',
                    data: [
                        {
                            name: '',
                            data: res.data.dyfb.dsdy_info.top5_num
                        }
                    ]
                })
                setduishou(res.data)
                setisloading(false)
            })
        }
        getData()
    }, [data, startDate, endDate])
    useEffect(() => {
        function gmpie() {
            if (gmtype === '上游') {
                setgmRatio({
                    total: {
                        title: data.company_info[0].IS_CYDW === 1 ? '成员单位(家)' : '对手总计(家)',
                        figure: duishou.dsgm_cydw.cydw_info.sxy_pie_chart.sy_num
                    },
                    data: duishou.dsgm_cydw.cydw_info.sxy_pie_chart.sy_num_list
                })
            }
            if (gmtype === '下游') {
                setgmRatio({
                    total: {
                        title: data.company_info[0].IS_CYDW === 1 ? '成员单位(家)' : '对手总计(家)',
                        figure: duishou.dsgm_cydw.cydw_info.sxy_pie_chart.xy_num
                    },
                    data: duishou.dsgm_cydw.cydw_info.sxy_pie_chart.xy_num_list
                })
            }
        }
        duishou && gmpie()
    }, [gmtype, duishou])
    useEffect(() => {
        function hypie() {
            if (hytype === '上游') {
                sethyRatio({
                    total: {
                        title: '涉及行业(种)',
                        figure: duishou.hyfb.dshy_info.sxy_pie_chart.sy_gbhyml_num
                    },
                    data: duishou.hyfb.dshy_info.sxy_pie_chart.sy_gbhyml_num_list
                })
            }
            if (hytype === '下游') {
                sethyRatio({
                    total: {
                        title: '涉及行业(种)',
                        figure: duishou.hyfb.dshy_info.sxy_pie_chart.xy_gbhyml_num
                    },
                    data: duishou.hyfb.dshy_info.sxy_pie_chart.xy_gbhyml_num_list
                })
            }
        }
        duishou && hypie()
    }, [hytype, duishou])

    useEffect(() => {
        function gettrade() {
            tradecrowdAPI({
                company: data.company_info[0].GSMC,
                companytype: data.company_info[0].IS_CYDW,
                startDate,
                endDate
            }).then(res => {
                // res.data && setshequdata(res.data[0])
            if (res.data && res.data.length > 0) {
                const firstData = res.data[0];
                // 判断 edges 是否为空数组
                if (firstData.edges.length === 0) {
                    // 当 edges 为空时，将 shequdata 置为空
                    setshequdata(null); // 或者使用空对象 {}
                } else {
                    // 否则正常设置 shequdata
                    setshequdata(firstData);
                }
            } else {
                // res.data 不存在或为空数组时，也置空 shequdata
                setshequdata(null);
            }                
            })
        }
        gettrade()
    }, [data, startDate, endDate])

    const report_download = () => {
        // setFlowLoading(true)
        // 生成报告
        exportgenerateAPI({
            company: data.company_info[0].GSMC,
        }).then(res => {
            if (res.code == 200) {
                messageApi.open({
                    type: 'success',
                    content: res.message,
                });
                axios.get(`http://192.168.1.188:9000/kshx/download-reportfile?uuid=${res.data}`, {
                    responseType: 'blob', 
                    headers: {
                        Authorization: 'Bearer ' + localStorage.getItem('kshxtoken')
                    }
                }).then(res => {
                    const blob = new Blob([res.data], { type: res.headers['content-type'] });
                    let fileName = data.company_info[0].GSMC + '.docx'; // 默认名
                    // 创建下载链接并触发下载
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                }).catch(err => {
                    console.error('文件下载失败:', err);
                });
            }else{
                messageApi.open({
                    type: 'error',
                    content: res.message,
                });
            }
        }).catch(()=>{
            messageApi.open({
                type: 'error',
                content: '报告生成失败！',
            });
        }).finally(() => {
            // setFlowLoading(false)
        })
    }
    return (
        <Spin tip="页面加载中..." spinning={isloading} size='large'>
            <div className='rival-container'>
                <Flex justify='center' className='title'>
                    <Title level={3}>{data.company_info[0].GSMC}</Title>
                    {contextHolder}
                    <Button className='btn' type='link' icon={<ExportOutlined />} onClick={report_download}>导出报告</Button>
                </Flex>
                <Flex justify='center' style={{ marginTop: '14px' }}>
                    <RangePicker onChange={handleDate} defaultValue={[dayjs(startDate, 'YYYY-MM-DD'), dayjs(endDate, 'YYYY-MM-DD')]}></RangePicker>
                    {/* <DatePicker onChange={handleDate} defaultValue={dayjs('2024', 'YYYY')} picker="year" /> */}
                </Flex>
                {feature && <Card className='indicator-wrap'>
                    <Flex>
                        <Flex align='center'>
                            <img src={icon} style={{ width: '22px', marginRight: '8px' }} alt='' />
                            <Title level={5}>对手特征</Title>
                        </Flex>
                    </Flex>
                    <Paragraph className='desc'>该企业交易对手以 <Text strong>{feature.qygm}</Text> 为主，占所有交易总额 <Text strong>{feature.jezb}</Text>。交易对手主要分布在 <Text strong>{feature.sssf}</Text> 等。主要涉及行业 <Text strong>{feature.sjhy}</Text> 等。</Paragraph>
                </Card>}
                <Flex vertical gap={16}>
                    <Flex style={{ marginTop: '24px' }}>
                        <Title level={5}>交易社群</Title>
                    </Flex>
                    <div className="tags-container tags-container3 ">
                        <Flex className="title" justify="space-between" align="center">
                            <p>{data.company_info[0].GSMC}</p>
                            <Button onClick={() => toggleFull('.tags-container3')} size="small" color="primary"
                                variant="text" icon={isFullScreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}>{isFullScreen ? '退出全屏' : '全屏查看'}</Button>
                        </Flex>
                        <Flex vertical justify="center" className="chart-box" style={{ width: '100%', height: chartBoxHeight }}>
                            {shequdata && <Jiaoyi data={shequdata} />}
                            {!shequdata && <Empty description='暂无数据' image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>}
                            {/* {shequdata ? <Jiaoyi data={shequdata} /> : null} */}
                        </Flex>
                    </div>
                </Flex>
                { IS_CYDW != '0' &&
                <Flex justify='center' className='topic' style={{ marginTop: '24px' }}>
                    <Title level={4}>{data.company_info[0].IS_CYDW === 1 ? '对手规模情况' : '成员单位分布'}</Title>
                </Flex>}
                { IS_CYDW != '0' &&
                    <Flex gap={16} style={{ marginTop: 16 }}>
                    <Card className='chart-card'>
                        <Flex justify="space-between">
                            <Title level={5}>{data.company_info[0].IS_CYDW === 1 ? '规模占比' : '成员单位占比'}</Title>
                            <Segmented
                                options={['上游', '下游']}
                                onChange={(value) => {
                                    setgmtype(value); // string
                                }}
                            />
                        </Flex>
                        <div className="chart-box" style={{ width: '100%', height: chartBoxH }}>
                            {gmRatio && <PieChart data={gmRatio} />}
                        </div>
                    </Card>
                    <Card className='chart-card'>
                        <Title level={5}>上下游数量统计</Title>
                        <Flex vertical justify="center" className="chart-box" style={{ width: '100%', height: chartBoxH }}>
                            {gmstatisticsData && <BarChart xAxisData={gmxAxisData} data={gmstatisticsData} />}
                            {!gmstatisticsData && <Empty description='暂无数据' image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>}
                        </Flex>
                    </Card>
                </Flex>}
                {/* {data.company_info[0].IS_CYDW === 1 && 
                    <>
                        <Flex justify='center' className='topic' style={{ marginTop: '24px' }}>
                            <Title level={4}>成员单位分布</Title>
                        </Flex>
                        <Flex gap={16} style={{ marginTop: 16 }}>
                            <Card className='chart-card'>
                                <Flex justify="space-between">
                                    <Title level={5}>成员单位占比</Title>
                                    <Segmented
                                        options={['上游', '下游']}
                                        onChange={(value) => {
                                            setgmtype(value); // string
                                        }}
                                    />
                                </Flex>
                                <div className="chart-box" style={{ width: '100%', height: chartBoxH }}>
                                    {gmRatio && <PieChart data={gmRatio} />}
                                </div>
                            </Card>
                            <Card className='chart-card'>
                                <Title level={5}>上下游数量统计</Title>
                                <Flex vertical justify="center" className="chart-box" style={{ width: '100%', height: chartBoxH }}>
                                    {gmstatisticsData && <BarChart xAxisData={gmxAxisData} data={gmstatisticsData} />}
                                    {!gmstatisticsData && <Empty description='暂无数据' image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>}
                                </Flex>
                            </Card>
                        </Flex>
                    </>
                } */}
                {IS_CYDW != '0' &&
                <Flex justify='center' className='topic' style={{ marginTop: '24px' }}>
                    <Title level={4}>对手地域分布</Title>
                </Flex>}
                {IS_CYDW != '0' &&
                    <Flex gap={16} style={{ marginTop: 16 }}>
                    <Card className='chart-card'>
                        <Title level={5}>全国分布</Title>
                        <div className="chart-box" style={{ width: '100%', height: chartBoxH }}>
                            <DistributionDiagram dataList={fbdataList} />
                        </div>
                    </Card>
                    <Card className='chart-card'>
                        <Title level={5}>TOP5省份</Title>
                        <Flex vertical justify="center" className="chart-box" style={{ width: '100%', height: chartBoxH }}>
                            {dyxAxisData.length > 0 && <BarChart xAxisData={dyxAxisData} data={dystatisticsData} isTurn />}
                            {!dyxAxisData.length > 0 && <Empty description='暂无数据' image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>}
                        </Flex>
                    </Card>
                </Flex>}
                <Flex justify='center' className='topic' style={{ marginTop: '24px' }}>
                    <Title level={4}>对手行业分布</Title>
                </Flex>
                <Flex gap={16} style={{ marginTop: 16 }}>
                    <Card className='chart-card'>
                        <Flex justify="space-between">
                            <Title level={5}>行业类型占比</Title>
                            <Segmented
                                options={['上游', '下游']}
                                onChange={(value) => {
                                    sethytype(value); // string
                                }}
                            />
                        </Flex>
                        <div className="chart-box" style={{ width: '100%', height: chartBoxH }}>
                            {/* {hyRatio && <PieChart data={hyRatio} />} */}
                            {hyRatio ? <PieChart data={hyRatio} /> : null}
                        </div>
                    </Card>
                    <Card className='chart-card'>
                        <Title level={5}>上下游数量统计</Title>
                        <Flex vertical justify="center" className="chart-box" style={{ width: '100%', height: chartBoxH }}>
                            {hyxAxisData && <BarChart xAxisData={hyxAxisData} data={hystatisticsData} />}
                            {!hyxAxisData && <Empty description='暂无数据' image={Empty.PRESENTED_IMAGE_SIMPLE}></Empty>}
                            {/* {hyxAxisData && hystatisticsData ? (
                                <BarChart xAxisData={hyxAxisData} data={hystatisticsData} />
                            ) : null} */}
                        </Flex>
                    </Card>
                </Flex>
            </div>
        </Spin>
    )
}
